package com.weilele.leisure.time.ui.holder


import android.view.View
import androidx.lifecycle.Observer
import com.google.android.exoplayer2.offline.Download
import com.weilele.leisure.time.R
import com.weilele.leisure.time.bean.db.CommonDb
import com.weilele.leisure.time.bean.db.HistoryVideoBean
import com.weilele.leisure.time.databinding.HolderCacheDetailBinding
import com.weilele.leisure.time.ui.dialog.TransformingMediaDialog
import com.weilele.leisure.time.ui.player.TransformingMediaHelper
import com.weilele.mvvm.adapter.MvvmHolder
import com.weilele.mvvm.adapter.mvvmRcvAdapter
import com.weilele.mvvm.base.livedata.StatusData
import com.weilele.mvvm.utils.activity.*
import com.weilele.mvvm.utils.coroutine.switchToThread
import com.weilele.mvvm.utils.formJsonString
import com.weilele.mvvm.utils.formatLength
import com.weilele.mvvm.utils.keepTwoPoint
import com.yizisu.playerlibrary.IYzsPlayer
import com.yizisu.playerlibrary.activity.FullScreenVideoActivity
import com.yizisu.playerlibrary.helper.SimplePlayerListener
import com.yizisu.playerlibrary.service.download.PlayerDownload
import kotlinx.coroutines.CoroutineScope


class CacheDetailHolder : MvvmHolder<Download, HolderCacheDetailBinding>,
    Observer<StatusData<TransformingMediaHelper.TransformingInfo>> {

    companion object {
        fun toAdapter() = mvvmRcvAdapter(CacheDetailHolder::class.java, ::checkSame, ::checkSame)
        private fun checkSame(old: Download?, new: Download?): Boolean {
            return old?.percentDownloaded != new?.percentDownloaded
                    && old?.request?.id != new?.request?.id
                    && old?.state != new?.state
        }
    }

    private var videoCacheBean: HistoryVideoBean? = null

    constructor(binding: HolderCacheDetailBinding) : super(binding)
    constructor(itemView: View) : super(itemView)

    init {
        mBinding.ringView.onClick {
            dataWhenBind?.request?.id?.let {
                PlayerDownload.getDownload(it)?.let { data ->
                    when (data.state) {
                        Download.STATE_COMPLETED -> {

                        }
                        Download.STATE_DOWNLOADING -> {
                            PlayerDownload.stopDownload(data.request.id, 1)
                        }
                        Download.STATE_FAILED,
                        Download.STATE_QUEUED,
                        Download.STATE_STOPPED -> {
                            PlayerDownload.resumeDownload(data.request.id)
//                        updateProgress(PlayerDownload.getDownload(data.request.id))
                        }
                        Download.STATE_REMOVING -> {

                        }
                        Download.STATE_RESTARTING -> {

                        }
                    }
                }
            }
        }
        itemView.onClick { view ->
            val data = dataWhenBind ?: return@onClick
            val bean =
                videoCacheBean ?: String(data.request.data).formJsonString<HistoryVideoBean>()
            val url = data.request.uri.toString()
            CommonDb.getHistoryPlayVideos().forEach { h ->
                if (h.playUrl == url) {
                    bean.currentDuration = h.currentDuration
                    bean.totalDuration = h.totalDuration
                }
            }
            FullScreenVideoActivity.start(
                view.getActivity(),
                url,
                "${bean.title} ${bean.playTitle} ${bean.listName}",
                bean.currentDuration,
                object : SimplePlayerListener<IYzsPlayer.Model> {
                    override suspend fun onTick(
                        playerModel: IYzsPlayer.Model,
                        scope: CoroutineScope
                    ) {
                        super.onTick(playerModel, scope)
                        switchToThread {
                            saveToDb(playerModel.currentDuration, playerModel.totalDuration)
                        }
                    }

                    override fun onPrepare(playerModel: IYzsPlayer.Model?) {
                        super.onPrepare(playerModel)
                        playerModel?.let {
                            saveToDb(playerModel.currentDuration, playerModel.totalDuration)
                        }
                    }
                }
            )
        }
        mBinding.tvChange.onClick {
            dataWhenBind?.let { data ->
                if (TransformingMediaHelper.startTransformer(
                        it,
                        data,
                        mBinding.name.text.toString()
                    )
                ) {
                    addTransformListener(data)
                }
            }
        }
        itemView.addOnAttachStateChangeListener(object : View.OnAttachStateChangeListener {
            override fun onViewAttachedToWindow(v: View?) {

            }

            override fun onViewDetachedFromWindow(v: View?) {
                onViewDetachedFromWindow()
            }
        })
    }

    override fun onViewDetachedFromWindow() {
        super.onViewDetachedFromWindow()
        dataWhenBind?.let {
            TransformingMediaHelper.checkTaskData(it)?.removeObserver(this)
        }
    }

    /**
     * 数据保存到数据库
     */
    private fun saveToDb(current: Long, total: Long) {
        videoCacheBean?.let {
            it.currentDuration = current
            it.totalDuration = total
            CommonDb.savePlayVideo(it)
        }
    }

    override fun bindData(data: Download) {
        addTransformListener(data)
        val videoCacheByte = data.request.data
        updateProgress(data)
        if (videoCacheByte.isNotEmpty()) {
            val bean = String(videoCacheByte).formJsonString<HistoryVideoBean>()
            videoCacheBean = bean
            mBinding.name.text = "${bean.playTitle}(${bean.listName})"
        }
    }

    /**
     * 添加监听
     */
    private fun addTransformListener(data: Download) {
        //region 进度转换监听
        TransformingMediaHelper.checkTaskData(data)?.let {
            it.removeObserver(this)
            it.observeForever(this)
        }
        //endregion
    }

    /**
     * 更新进度
     */
    fun updateProgress(data: Download) {
        mBinding.des.text = if (data.percentDownloaded.toInt() == 100) {
            mBinding.ringView.invisible()
            mBinding.tvChange.visible()
            "已完成 / ${data.bytesDownloaded.formatLength()}"
        } else {
            mBinding.ringView.visible()
            mBinding.tvChange.gone()
            "${data.bytesDownloaded.formatLength()} / ${
                (data.bytesDownloaded * 100 / data.percentDownloaded).toLong().formatLength()
            }"
        }
        data.percentDownloaded
        mBinding.ringView.progress = data.percentDownloaded / 100
        mBinding.ringView.progressText = when (data.state) {
            Download.STATE_COMPLETED -> {
                "已完成"
            }
            Download.STATE_DOWNLOADING -> {
                "下载中"
            }
            Download.STATE_FAILED -> {
                "已失败"
            }
            Download.STATE_QUEUED -> {
                "等待中"
            }
            Download.STATE_REMOVING -> {
                "删除中"
            }
            Download.STATE_RESTARTING -> {
                "重试中"
            }
            Download.STATE_STOPPED -> {
                "已暂停"
            }
            else -> {
                ""
            }
        }
    }

    /**
     * 转换进度回调
     */
    override fun onChanged(data: StatusData<TransformingMediaHelper.TransformingInfo>?) {
        data?.data?.let {
            mBinding.tvChange.text = it.message
            if (it.success) {
                mBinding.tvChange.gone()
            }
        }
    }
}